import { filterTodolist } from '../util/todoStorage.js'
import { ref, onMounted, onUnmounted, computed } from 'vue'

const hashArray = ['all', 'completed', 'active']
export function useFilter(todoListRef) {
  const visiblityRef = ref('all')
  const hashChange = () => {
    let hashcontent = location.hash.replace(/#\/?/, '')
    if (hashArray.includes(hashcontent)) {
      visiblityRef.value = hashcontent
    } else {
      location.hash = ''
      visiblityRef.value = 'all'
    }
  }
  onMounted(() => {
    window.addEventListener('hashchange', hashChange)
  })
  onUnmounted(() => {
    window.removeEventListener('hashchange', hashChange)
  })
  const filterTodoRef = computed(() => {
    return filterTodolist(todoListRef.value, visiblityRef.value)
  })
  const computedLengthRef = computed(() => {
    return filterTodolist(todoListRef.value, 'completed').length
  })
  const activeLengthRef = computed(() => {
    return filterTodolist(todoListRef.value, 'active').length
  })
  return {
    visiblityRef,
    filterTodoRef,
    computedLengthRef,
    activeLengthRef
  }
}